<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务卡编码" prop="taskCardId">
        <el-input
          v-model="queryParams.taskCardId"
          placeholder="请输入任务卡编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="产品编码" prop="prodId">
        <el-input
          v-model="queryParams.prodId"
          placeholder="请输入产品编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务编码" prop="taskId">
        <el-input
          v-model="queryParams.taskId"
          placeholder="请输入任务编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="计划编码" prop="planId">-->
<!--        <el-input-->
<!--          v-model="queryParams.planId"-->
<!--          placeholder="请输入计划编码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="任务状态(0未完成/1已完成)" prop="taskCardStatus">
        <el-select v-model="queryParams.taskCardStatus" placeholder="请选择任务状态(0未完成/1已完成)" clearable>
          <el-option
            v-for="dict in dict.type.card_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="加工数量" prop="procNum">
        <el-input
          v-model="queryParams.procNum"
          placeholder="请输入加工数量"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务开始时间" prop="taskTime">
        <el-date-picker clearable
          v-model="queryParams.taskTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择任务开始时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务结束时间" prop="taskFinTime">
        <el-date-picker clearable
          v-model="queryParams.taskFinTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择任务结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="生产进度" prop="productionSchedule">
        <el-input
          v-model="queryParams.productionSchedule"
          placeholder="请输入生产进度"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:card:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:card:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:card:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:card:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="cardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="车间任务卡id" align="center" prop="id" />
      <el-table-column label="任务卡编码" align="center" prop="taskCardId" />
      <el-table-column label="产品编码" align="center" prop="prodId" />
      <el-table-column label="任务编码" align="center" prop="taskId" />
<!--      <el-table-column label="计划编码" align="center" prop="planId" />-->
<!--      <el-table-column label="生产进度" align="center" prop="productionSchedule" >-->

      <el-table-column label="生产进度" align="center" prop="productionSchedule" width="280">
        <template slot-scope="scope">
          <el-progress
            :text-inside="true"
            :stroke-width="25"
            :percentage="scope.row.productionSchedule"
            :status="scope.row.productionSchedule === 100 ? 'success' : 'warning'"
          />
        </template>
      </el-table-column>

      <el-table-column label="加工数量" align="center" prop="procNum" />
      <el-table-column label="任务开始时间" align="center" prop="taskTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务结束时间" align="center" prop="taskFinTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.taskFinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态(0未完成/1已完成)" align="center" prop="taskCardStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.card_status" :value="scope.row.taskCardStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleWorkOpen(scope.row)"
            v-hasPermi="['system:card:edit']"
          >报工</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:card:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:card:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改车间任务卡对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务卡编码" prop="taskCardId">
          <el-input v-model="form.taskCardId" placeholder="请输入任务卡编码" />
        </el-form-item>
        <el-form-item label="产品编码" prop="prodId">
          <el-input v-model="form.prodId" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="任务编码" prop="taskId">
          <el-input v-model="form.taskId" placeholder="请输入任务编码" />
        </el-form-item>

<!--        <el-form-item label="计划编码" prop="planId">-->
<!--          <el-input v-model="form.planId" placeholder="请输入计划编码" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="计划编码" prop="planId">-->
<!--          <el-select v-model="form.planId" filterable placeholder="请选择">-->
<!--            <el-option v-for="item in planinfoselectoption" :key="item.id" :label="item.planId" :value="item.planId">-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->

        <el-form-item label="任务状态(0未完成/1已完成)" prop="taskCardStatus">
          <el-select v-model="form.taskCardStatus" placeholder="请选择任务状态(0未完成/1已完成)">
            <el-option
              v-for="dict in dict.type.card_status"
              :key="dict.value"
              :label="dict.label"
:value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="加工数量" prop="procNum">
          <el-input v-model="form.procNum" placeholder="请输入加工数量" />
        </el-form-item>
        <el-form-item label="任务开始时间" prop="taskTime">
          <el-date-picker clearable
            v-model="form.taskTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择任务开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="任务结束时间" prop="taskFinTime">
          <el-date-picker clearable
            v-model="form.taskFinTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择任务结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="生产进度" prop="productionSchedule">
          <el-input v-model="form.productionSchedule" placeholder="请输入生产进度" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 报工    -->
    <el-dialog :title="title" :visible.sync="workOpen" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务卡编码" prop="taskCardId"label-width="100px">
          <el-input v-model="form.taskCardId" placeholder="请输入任务卡编码" />
        </el-form-item>

        <el-form-item label="产品编码" prop="prodId" label-width="100px">
          <el-input v-model="form.prodId" placeholder="请输入产品编码" />
        </el-form-item>

        <el-form-item label="总加工数量" prop="taskCardId" label-width="100px">
          <el-input v-model="form.procNum" placeholder="请输入任务卡编码" />
        </el-form-item>
        <div style="margin-bottom: 50px;"></div>
        <el-divider>报 工</el-divider>
        <div style="margin-bottom: 50px;"></div>
        <el-card shadow="always" style="border-radius: 15px;">
          <el-table style="border-radius: 15px;" v-loading="loading" border :data="form.mtrs">
            <el-table-column label="工序"  prop="processId" align="center">
<!--              <template slot-scope="scope" >-->

<!--              </template>-->
            </el-table-column>

            <el-table-column label="加工数量" align="center"  width="230px" >
              <template slot-scope="scope">
                <el-input-number id="inputNumber" v-model:value="scope.row.workNum" :min="0" :precision="0" />
              </template>
            </el-table-column>

            <el-table-column label="待加工数量" align="center"  width="230px" prop="waitNum">
<!--              <template slot-scope="scope">-->
<!--                <el-input-number id="inputNumber" v-model:value="scope.row.waitNum" :min="0" :precision="0" />-->
<!--              </template>-->
            </el-table-column>

            <el-table-column label="已加工数量" align="center"  width="230px" prop="finNum">
<!--              <template slot-scope="scope">-->
<!--                <el-input-number id="inputNumber" v-model:value="scope.row.finNum" :min="0" :precision="0" />-->
<!--              </template>-->
            </el-table-column>


            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" >
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="workUpdate(scope.$index, scope.row)"
                           v-hasPermi="['mes:proinfo:edit']">确认报工</el-button>

              </template>
            </el-table-column>
          </el-table>
        </el-card>


      </el-form>
      <div slot="footer" class="dialog-footer">

        <el-button @click="cancel">返 回</el-button>
      </div>
    </el-dialog>



  </div>
</template>

<script>
import {listCard, getCard, delCard, addCard, updateCard, getWorkMsg, getWorkIsFinish} from "@/api/system/card";
import {listInspection} from "@/api/system/inspection";
import {listPlan} from "@/api/system/plan";
import {listWork, updateWork} from "@/api/system/work";
import {updateTask} from "@/api/system/task";

export default {
  name: "Card",
  dicts: ['card_status'],
  data() {
    return {
      //计划编码下拉框数据
      planinfoselectoption: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 车间任务卡表格数据
      cardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //
      workOpen:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskCardId: null,
        prodId: null,
        taskId: null,
        planId: null,
        taskCardStatus: null,
        procNum: null,
        taskTime: null,
        taskFinTime: null,
        productionSchedule: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskCardId: [
          { required: true, message: "任务卡编码不能为空", trigger: "blur" }
        ],
        prodId: [
          { required: true, message: "产品编码不能为空", trigger: "blur" }
        ],
        taskId: [
          { required: true, message: "任务编码不能为空", trigger: "blur" }
        ],
        planId: [
          { required: true, message: "计划编码不能为空", trigger: "blur" }
        ],
        taskCardStatus: [
          { required: true, message: "任务状态(0未完成/1已完成)不能为空", trigger: "change" }
        ],
        procNum: [
          { required: true, message: "加工数量不能为空", trigger: "blur" }
        ],
        taskTime: [
          { required: true, message: "任务开始时间不能为空", trigger: "blur" }
        ],
        taskFinTime: [
          { required: true, message: "任务结束时间不能为空", trigger: "blur" }
        ],
        productionSchedule: [
          { required: true, message: "生产进度不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询车间任务卡列表 */
    getList() {
      this.loading = true;
      listCard(this.queryParams).then(response => {
        this.cardList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
      //计划编码列表
      listPlan().then((res) => {
        this.planinfoselectoption = res.rows;
      })
    },
    //报工按钮
    handleWorkOpen(row) {
      this.reset();
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data;
        this.workOpen = true;
        //根据车间任务卡拿到所有的工序的报工信息（id值唯一确定）
        getWorkMsg(this.form.taskCardId).then((response)=>{
          this.form.mtrs = response.data;
          this.form.allProcessWorkNum = 0;
          this.form.taskCardAllWorkNum = 0;
          this.form.mtrs.forEach((item) => {
            item.workNum = 0;
            this.form.allProcessWorkNum = this.form.allProcessWorkNum + item.finNum;
            this.form.taskCardAllWorkNum = this.form.taskCardAllWorkNum + (item.finNum + item.waitNum);
          });
          console.log("已加工：" + this.form.allProcessWorkNum + "总需要加工：" + this.form.taskCardAllWorkNum);
          //this.form.mtrs = [{processId:"工序1",workNum:0,waitNum:10,finNum:0},{processId:"工序2",workNum:0,waitNum:10,finNum:0}];
          this.title = "报工";
        });


      });
    },
    //确认报工按钮
    workUpdate(index, row){
      if(this.form.mtrs[index].finNum === this.form.procNum){
        this.$modal.msgError("该工序已完成");
        this.form.mtrs.forEach((item) => {
          item.workNum = 0;
        });
      }else if(row.workNum === 0){
        this.$modal.msgError("请输入报工数量");
      }else if((this.form.mtrs[index].finNum + row.workNum) > this.form.procNum){
        this.$modal.msgError("报工数量太大");
      }
      else{
        this.form.mtrs[index].waitNum = this.form.mtrs[index].waitNum - row.workNum;
        this.form.mtrs[index].finNum = this.form.mtrs[index].finNum + row.workNum;

        //生产进度
        // console.log("生产进度：" + this.form.productionSchedule);
        // this.form.productionSchedule = 20;
        console.log("已加工：" + this.form.allProcessWorkNum);
        console.log("总需要加工：" + this.form.taskCardAllWorkNum);
        this.form.allProcessWorkNum = this.form.allProcessWorkNum + row.workNum;
        this.form.productionSchedule = (this.form.allProcessWorkNum) / (this.form.taskCardAllWorkNum);
        this.form.productionSchedule = this.form.productionSchedule * 100;
        console.log("生产进度：" + this.form.productionSchedule);

        //如果生产进度为100%
        if(this.form.productionSchedule === 100){
          this.form.taskCardStatus = 1;

        }

        updateWork(this.form.mtrs[index]).then(response => {
          getWorkMsg(this.form.taskCardId).then((response)=>{
            this.form.mtrs = response.data;
            this.form.mtrs.forEach((item) => {
              item.workNum = 0;
            });
          });

          updateCard(this.form).then(response => {

            this.getList();

            //判断车间任务是否完成接口
            getWorkIsFinish(this.form.taskId).then((response)=>{
              if(response.data){
                this.$modal.msgSuccess("车间任务已完成，请完工入库");
              }
            });

          });

          this.$modal.msgSuccess("报工成功");
        });

      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.workOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskCardId: null,
        prodId: null,
        taskId: null,
        planId: null,
        taskCardStatus: null,
        procNum: null,
        taskTime: null,
        taskFinTime: null,
        productionSchedule: null,
        //所有当前任务卡所有工序的已加工数量
        allProcessWorkNum: 0,
        //任务卡总的加工数
        taskCardAllWorkNum: 0,
        mtrs:[],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加车间任务卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getCard(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改车间任务卡";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCard(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除车间任务卡编号为"' + ids + '"的数据项？').then(function() {
        return delCard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/card/export', {
        ...this.queryParams
      }, `card_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
